package com.bascker.algorithm.base.linkedlist;

import javax.annotation.Nonnull;
import java.util.Objects;

/**
 * 双向链表
 *
 * @param <T>
 */
public class DoublyLinkedList<T> {

    private DoublyListNode<T> head;

    private DoublyListNode<T> tail;

    private int length;

    public DoublyLinkedList() {

    }

    public void addHead(@Nonnull final DoublyListNode<T> node) {
        if (Objects.isNull(head) && Objects.isNull(tail)) {
            head = tail = node;
            return;
        }

        head.setPre(node);
        node.setNext(head);

        length++;
    }

    public void addTail(@Nonnull final DoublyListNode<T> node) {
        if (Objects.isNull(head) && Objects.isNull(tail)) {
            head = tail = node;
            return;
        }

        tail.setNext(node);
        node.setPre(tail);
        length++;
    }

    public void remove(@Nonnull final DoublyListNode<T> node) {
        final DoublyListNode<T> pre = node.getPre();
        final DoublyListNode<T> next = node.getNext();

        if (Objects.nonNull(pre)) {
            pre.setNext(next);
        }

        if (Objects.nonNull(next)) {
            next.setPre(pre);
        }

        node.setPre(null);
        node.setNext(null);

        length--;
    }

    public DoublyListNode<T> removeHead() {
        if (Objects.isNull(head)) {
            return null;
        }

        final DoublyListNode<T> first = head;
        remove(first);
        return first;
    }

    public DoublyListNode<T> removeTail() {
        if (Objects.isNull(tail)) {
            return null;
        }

        final DoublyListNode<T> last = tail;
        remove(last);
        return last;
    }

    public int getLength() {
        return length;
    }


}
